﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using NPOI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZhuXingFamilys.Help;
using ZhuXingFamilys.MainViewModel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using ZhuXingFamilys.ExportExcel.utils;
using RevitAddInDeployer;
using ZhuXingFamilys.utils;
using System.Web;

namespace ZhuXingFamilys.MainFamilyView
{
    /// <summary>
    /// FamilyAttribute.xaml 的交互逻辑
    /// </summary>
    public partial class FamilyAttribute : Page, IDockablePaneProvider
    {
        UIApplication uiApp = null;
        public static string FileAddress;
        public FamilyAttribute(UIControlledApplication application)
        {
            InitializeComponent();
            // 获得UIApplication
            var flag = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod;
            this.uiApp = (Autodesk.Revit.UI.UIApplication)application.GetType().InvokeMember("getUIApplication", flag, Type.DefaultBinder, application, null);
            // 注册空闲事件
            //application.Idling += Application_Idling;

            FileAddress = Set.settingaddress("Setup.ini");

        }
        // 空闲事件 
        private void Application_Idling(object sender, Autodesk.Revit.UI.Events.IdlingEventArgs e)
        {
            UIApplication uiapp = sender as UIApplication;

            // 修改选项卡激活时，打开筑星族属性窗口
            paneShow(uiapp);
            // 获取选择的构件属性
            getAttribute(uiapp);

        }
        // 修改选项卡激活时，打开筑星族属性窗口
        DockablePaneId paneId = new DockablePaneId(new Guid("321044f7-b0b2-4b1c-af18-e71a19252be0"));
        Autodesk.Windows.RibbonTab tab = null;
        private void paneShow(UIApplication uiapp)
        {
            if (tab == null)
            {
                foreach (Autodesk.Windows.RibbonTab tabInTabs in Autodesk.Windows.ComponentManager.Ribbon.Tabs)
                {
                    if (tabInTabs.Id == "Modify")
                    {
                        tab = tabInTabs;
                    }
                }
            }
            UIDocument uiDoc = uiapp.ActiveUIDocument;
            if (uiDoc != null)
            {
                DockablePane pane = uiapp.GetDockablePane(paneId);
                // 打开筑星属性窗口
                if (tab.IsActive && !pane.IsShown())
                {
                    pane.Show();
                }
                // 关闭筑星属性窗口
                //if (!tab.IsActive && pane.IsShown())
                //{
                //    pane.Hide();
                //}
            }
        }

        // 获取选择的构件属性
        ElementId selectedId = null;
        private void getAttribute(UIApplication uiapp)
        {
            DockablePane pane = uiapp.GetDockablePane(paneId);
            if (pane.IsShown())
            {
                UIDocument uiDoc = uiapp.ActiveUIDocument;
                if (uiDoc != null)
                {
                    Document doc = uiDoc.Document;
                    Selection s = uiDoc.Selection;
                    var ids = s.GetElementIds();
                    // 当前选中了一个族文件 并且发生的变化
                    if (ids.Count == 1)
                    {
                        if (ids.First() != selectedId)
                        {
                            Element el = doc.GetElement(ids.First());
                            string familyNumber = getElementTypeParameter(doc, el, "族库编号");
                            string familyName = getElementTypeParameter(doc, el, "项目名称");
                            string familyFeature = getElementTypeParameter(doc, el, "项目特征");
                            string typeName = el.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).AsValueString();
                            this.FamilyNumber.Text = familyNumber;
                            this.FamilyName.Text = familyName;
                            this.FamilyFeature.Text = familyFeature;
                            this.TypeName.Text = typeName;
                            try
                            {
                                picinfo.Source = getImg(FileAddress, typeName);
                            }
                            catch (Exception)
                            {
                                picinfo.Source = CsAddpanel.convertFromBitmap(Properties.Resource.公共族库);
                            }


                            selectedId = ids.First();
                        }
                    }
                    else if (this.FamilyNumber.Text != null && this.FamilyName.Text != null)
                    {
                        this.FamilyNumber.Text = null;
                        this.FamilyName.Text = null;
                        this.FamilyFeature.Text= null;
                        this.TypeName.Text = null;
                        this.picinfo.Source = CsAddpanel.convertFromBitmap(Properties.Resource.公共族库); ;
                    }
                }
            }
        }
        // 获取图片
        private BitmapImage getImg(string path,string typeName)
        {
            string familyNodeID = string.Empty;
            ObservableCollection<FamilyFile> FamilyFiles = new ObservableCollection<FamilyFile>();
            //ObservableCollection<FamilyFile> FamilyFiles = CacheManagerHelper.Get<ObservableCollection<FamilyFile>>("FamilyFiles");
            if (FamilyFiles == null || FamilyFiles.Count == 0)
            {
                //ObservableCollection<FamilyFile> FamilyFiles = new ObservableCollection<FamilyFile>();
                DataSet FamilyDatas = new DataSet();
                string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
                string FamilySql = "SELECT FamilyName,FamilyNodeID FROM Family ";
                using (SqlConnection conn = new SqlConnection(constr))
                {
                    conn.Open();
                    SqlDataAdapter FamilyData = new SqlDataAdapter(FamilySql, conn);   //(查询语句和连接工具)
                    FamilyData.Fill(FamilyDatas);    //将适配器数据存入DataSet工具中
                    FamilyFiles = new ObservableCollection<FamilyFile>();
                    FamilyFile FamilyFile = null;
                    foreach (DataRow row in FamilyDatas.Tables[0].Rows)
                    {
                        FamilyFile = new FamilyFile();
                        FamilyFile.ImagePath = DataProcessor.ToValue(row, "FamilyName", "0");
                        FamilyFile.FamilyName = DataProcessor.ToValue(row, "FamilyName", "0");
                        FamilyFile.FamilyCategoryName = DataProcessor.ToValue(row, "FamilyCategoryName", "0");
                        FamilyFile.FamilyFileCategory = DataProcessor.ToValue(row, "FamilyFileCategory", "1");
                        FamilyFile.author = DataProcessor.ToValue(row, "author", "1");
                        FamilyFile.FamilyNodeID = DataProcessor.ToValue(row, "FamilyNodeID", "0");
                        FamilyFile.ProjectFeatures = DataProcessor.ToValue(row, "ProjectFeatures", "0");

                        FamilyFiles.Add(FamilyFile);
                    }
                    // 缓存
                    //CacheManagerHelper.Set<ObservableCollection<FamilyFile>>("FamilyFiles", FamilyFiles);
                }
            }

            FamilyFile ff = FamilyFiles.Where(f => f.FamilyName == typeName).FirstOrDefault();
            if (ff != null)
            {
                familyNodeID = ff.FamilyNodeID;
            }
            BitmapImage img = new BitmapImage();
            img.BeginInit();
            string ImageFullPath = path + "\\" + familyNodeID + "\\" + typeName + ".png";
            img.StreamSource = new MemoryStream(File.ReadAllBytes(ImageFullPath));
            img.EndInit();
            return img;
        }

        // 设置初始位置
        public void SetupDockablePane(DockablePaneProviderData data)
        {
            DockablePaneProviderData d = new DockablePaneProviderData();
            data.FrameworkElement = this;
            data.InitialState = new DockablePaneState()
            {
                DockPosition = DockPosition.Right,
                //MinimumHeight = 100
            };
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            picinfo.Source = CsAddpanel.convertFromBitmap(Properties.Resource.公共族库);
        }

        // 获取类型参数
        private string getElementTypeParameter(Document doc, Element ele, string parameterName)
        {
            ICollection<ElementId> vt = ele.GetValidTypes();
            Parameter p = null;
            foreach (var eid in vt)
            {
                Element e = doc.GetElement(eid);
                if (e.Name == ele.Name)//找到当前所选图元的族类型
                {
                    p = e.LookupParameter(parameterName);
                    if (p != null && p.AsString() != null)
                    {
                        return p.AsString();
                    }
                }
            }
            return "";
        }
    }
}
